package com.reliable.framework.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import java.security.KeyStore;
import java.time.Duration;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {
   @Bean
   public ElasticsearchClient elasticsearchClient() {
      CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
      credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "8jI9uyq1hFLQI_=rV9*o"));
      TrustStrategy trustAllStrategy = (chain, authType) -> {
         return true;
      };

      SSLContext sslContext;
      try {
         sslContext = SSLContextBuilder.create().loadTrustMaterial((KeyStore)null, trustAllStrategy).setProtocol("TLS").build();
      } catch (Exception var6) {
         throw new RuntimeException("Failed to create SSL context", var6);
      }

      RestClientBuilder builder = RestClient.builder(new HttpHost[]{new HttpHost("101.33.253.211", 9200, "http")}).setRequestConfigCallback((requestConfigBuilder) -> {
         requestConfigBuilder.setConnectTimeout((int)Duration.ofSeconds(5L).toMillis());
         requestConfigBuilder.setSocketTimeout((int)Duration.ofSeconds(60L).toMillis());
         return requestConfigBuilder;
      }).setHttpClientConfigCallback((httpClientBuilder) -> {
         httpClientBuilder.disableCookieManagement();
         httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
         httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
         httpClientBuilder.setSSLContext(sslContext);
         return httpClientBuilder;
      });
      ElasticsearchTransport transport = new RestClientTransport(builder.build(), new JacksonJsonpMapper());
      return new ElasticsearchClient(transport);
   }
}
    